package br.ucb.sacop.webservice;

import java.util.ArrayList;

import android.util.Log;
import br.ucb.sacop.bean.CalendarioShort;
import br.ucb.sacop.bean.PlanoDeEnsino;
import br.ucb.sacop.bean.TurmaShort;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class PlanoREST extends GenericREST{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String URL = getUrlWs()+"plano/";

	public PlanoDeEnsino getPlanoByTurma(int turmaId) throws Exception {
		Gson gsonTemp = new Gson();
		TurmaShort turma = new TurmaShort();
		turma.setTurmaId(turmaId);
		String clienteJSON = gsonTemp.toJson(turma);
		String[] resposta = new WebServiceClient().post(URL + "getPlano", clienteJSON);
		Log.i("sacopTeste", "RESPOSTA PLANO "+ resposta[0]);
		if (resposta[0].equals("200")) {
			Gson gson = new Gson();
			PlanoDeEnsino plano = gson.fromJson(resposta[1], PlanoDeEnsino.class);
			Log.i("sacopTeste", "plano de ensino "+ plano);
			return plano;
		} else {
			throw new Exception(resposta[1]);
		}
	}

	public ArrayList<CalendarioShort> getCalendariosById(Integer codigo) throws Exception {
		Gson gsonTemp = new Gson();
		PlanoDeEnsino plano = new PlanoDeEnsino();
		plano.setCodigo(codigo);
		String clienteJSON = gsonTemp.toJson(plano);
		String[] resposta = new WebServiceClient().post(URL+"getCalendarios", clienteJSON);
		Log.i("sacopTeste", "resposta " +resposta[0]);
		if (resposta[0].equals("200")) {
			Log.i("sacopTeste", "resposta[1] " +resposta[1]);
			Gson gson = new Gson();
			ArrayList<CalendarioShort> calendarios = new ArrayList<CalendarioShort>();
			JsonParser parser = new JsonParser();
			JsonObject jobj = parser.parse(resposta[1]).getAsJsonObject();
			try {
				JsonArray array = jobj.getAsJsonArray("calendarioShort");
				for (int i = 0; i < array.size(); i++) {
					calendarios.add(gson.fromJson(array.get(i), CalendarioShort.class));
				}
			} catch (ClassCastException e) {
				calendarios.add(gson.fromJson(jobj.get("calendarioShort"), CalendarioShort.class));
			}
			return calendarios;
		}else
			throw new Exception(resposta[1]);
	}

	 

}
